from sqlalchemy.orm import Session
from models.models import User
from passlib.context import CryptContext
import uuid
from datetime import datetime
from config.redis_config import redis_client, TOKEN_EXPIRE_TIME

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

class UserService:
    @staticmethod
    def create_user(db: Session, username: str, password: str):
        # 检查用户名是否已存在
        if db.query(User).filter(User.username == username).first():
            return None
            
        hashed_password = pwd_context.hash(password)
        user = User(username=username, password=hashed_password)
        db.add(user)
        db.commit()
        db.refresh(user)
        return user

    @staticmethod
    def authenticate_user(db: Session, username: str, password: str):
        user = db.query(User).filter(User.username == username).first()
        if not user or not pwd_context.verify(password, user.password):
            return None
        return user

    @staticmethod
    def create_token(user_id: int) -> str:
        # 生成新token
        token = str(uuid.uuid4())
        
        # 更新用户最后登录时间
        redis_client.set(f"token:{token}", str(user_id), ex=TOKEN_EXPIRE_TIME)
        
        # 保存用户最新token（用于单点登录）
        # redis_client.set(f"user:{user_id}:token", token)
        
        return token

    @staticmethod
    def logout(token: str):
        user_id = redis_client.get(f"token:{token}")
        if user_id:
            redis_client.delete(f"token:{token}")
            # redis_client.delete(f"user:{user_id}:token") 